package com.lkd.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.common.VMSystem;
import com.lkd.feign.VMService;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import entity.VendingMachineEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 自动补货任务生成Job
 */
@Component
@Slf4j
public class SupplyJob {

    @Autowired
    private VendingMachineService vendingMachineService;
    /**
     * 售货机扫描任务
     */
    @XxlJob("supplyJobHandler")
    public ReturnT<String> supplyJobHandler(String param) throws Exception {
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        int total = shardingVo.getTotal(); // 分片总数
        int index = shardingVo.getIndex(); // 当前分片索引
        log.info("分片参数  当前分片索引{}   总分片数{}",index,total);
        XxlJobLogger.log( "分片参数  当前分片索引"+index+"  总分片数"+total);
        //查询所有运营状态的售货机
        LambdaQueryWrapper<VendingMachineEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING);
        wrapper.apply("mod ( id," + total + ") = " + index); // 对id取模
        List<VendingMachineEntity> vendingMachineEntityList = vendingMachineService.list(wrapper);
        vendingMachineEntityList.forEach(vendingMachineEntity -> {
            XxlJobLogger.log("扫描售货机"+ vendingMachineEntity.getInnerCode());
            vendingMachineService.sendSupplyTask(vendingMachineEntity.getInnerCode());
        });
        return ReturnT.SUCCESS;
    }
}
